<template>
	<scroll-view class="chat-container" scroll-y :scroll-top="scrollTop" :style="{height: containerHeight + 'px'}"
		enable-back-to-top scroll-with-animation @scroll="handleScroll" @scrolltoupper="loadMore">
		<view v-for="(message, index) in messages" :key="index" class="message-wrapper">
			<!-- 对方的消息 -->
			<view v-if="message.senderId !== currentUserId" class="other-message">
				<image class="avatar" :src="otherAvatar" mode="aspectFill"></image>
				<view class="message-content">
					<view class="message-bubble other-bubble">
						<text>{{ message.content }}</text>
					</view>
					<view class="message-time">{{ formatTime(message.createTime) }}</view>
				</view>
			</view>

			<!-- 自己的消息 -->
			<view v-else class="my-message">
				<view class="message-content">
					<view class="message-bubble my-bubble">
						<text>{{ message.content }}</text>
					</view>
					<view class="message-time">{{ formatTime(message.createTime) }}</view>
				</view>
				<image class="avatar" :src="myAvatar" mode="aspectFill"></image>
			</view>
		</view>
	</scroll-view>
</template>

<script>
	export default {
		name: 'MessageList',
		props: {
			messages: {
				type: Array,
				required: true,
				default: () => []
			},
			currentUserId: {
				type: String,
				required: true
			},
			myAvatar: {
				type: String,
				default: ''
			},
			otherAvatar: {
				type: String,
				default: ''
			},
			hasMore: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				scrollTop: 0,
				containerHeight: 500,
				scrollToBottomFlag: true,
				loading: false,
				initialized: false
			}
		},
		mounted() {
			this.calculateHeight();
			this.$nextTick(() => {
				this.scrollToBottom();
				this.initialized = true;
			});
		},
		watch: {
			messages: {
				handler(newVal, oldVal) {
					this.$nextTick(() => {
						// 只有初始化完成后再自动滚动
						if (this.initialized && this.scrollToBottomFlag) {
							this.scrollToBottom();
						}
					});
				},
				deep: true
			}
		},
		methods: {
			calculateHeight() {
				try {
					const res = uni.getSystemInfoSync();
					this.containerHeight = res.windowHeight - 240;
				} catch (e) {
					console.error('获取系统信息失败', e);
					this.containerHeight = 500;
				}
			},

			formatTime(isoTime) {
				if (!isoTime) return '';

				const messageDate = new Date(isoTime);
				const now = new Date();

				const messageYear = messageDate.getFullYear();
				const messageMonth = (messageDate.getMonth() + 1).toString().padStart(2, '0');
				const messageDay = messageDate.getDate().toString().padStart(2, '0');
				const hours = messageDate.getHours().toString().padStart(2, '0');
				const minutes = messageDate.getMinutes().toString().padStart(2, '0');

				const currentYear = now.getFullYear();
				const currentMonth = (now.getMonth() + 1).toString().padStart(2, '0');
				const currentDay = now.getDate().toString().padStart(2, '0');

				if (messageYear !== currentYear) {
					return `${messageYear}-${messageMonth}-${messageDay} ${hours}:${minutes}`;
				} else if (messageMonth !== currentMonth || messageDay !== currentDay) {
					return `${messageMonth}-${messageDay} ${hours}:${minutes}`;
				} else {
					return `${hours}:${minutes}`;
				}
			},

			scrollToBottom() {
				this.scrollToBottomFlag = true;
				this.$nextTick(() => {
					this.scrollTop = Math.random() * 1000000; // 随机值确保滚动
				});
			},

			keepPosition(oldScrollHeight) {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.chat-container').boundingClientRect(data => {
						if (data) {
							this.scrollTop = data.scrollHeight - oldScrollHeight;
						}
					}).exec();
				});
			},

			getScrollHeight() {
				return new Promise(resolve => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.chat-container').boundingClientRect(data => {
						resolve(data ? data.scrollHeight : 0);
					}).exec();
				});
			},

			handleScroll(e) {
				const {
					scrollTop,
					scrollHeight
				} = e.detail;
				const clientHeight = this.containerHeight;
				this.scrollToBottomFlag = scrollTop > scrollHeight - clientHeight - 50;

				if (scrollTop < 20 && !this.loading && this.hasMore) {
					this.loadMore();
				}
			},

			loadMore() {
				if (this.loading || !this.hasMore) return;
				this.loading = true;
				this.$emit('load-more');
				setTimeout(() => {
					this.loading = false;
				}, 2000);
			}
		}
	}
</script>
<style lang="scss" scoped>
	.chat-container {
		padding: 20rpx;
		box-sizing: border-box;
		background-color: #f5f5f5;
	}

	.message-wrapper {
		margin-bottom: 30rpx;
	}

	.other-message,
	.my-message {
		display: flex;
		margin-bottom: 20rpx;
		align-items: flex-start;
	}

	.my-message {
		justify-content: flex-end;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
	}

	.message-content {
		max-width: 70%;
		display: flex;
		flex-direction: column;
	}

	.message-bubble {
		padding: 20rpx 30rpx;
		border-radius: 36rpx;
		position: relative;
		word-wrap: break-word;
		font-size: 32rpx;
		line-height: 1.4;
	}

	.other-bubble {
		background-color: #ffffff;
		border: 1px solid #eaeaea;
		margin-left: 20rpx;
		border-top-left-radius: 8rpx;
	}

	.my-bubble {
		background-color: #95ec69;
		margin-right: 20rpx;
		border-top-right-radius: 8rpx;
	}

	.message-time {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.other-message .message-time {
		text-align: left;
		padding-left: 30rpx;
	}

	.my-message .message-time {
		text-align: right;
		padding-right: 30rpx;
	}
</style>